'use client';
import { useEffect, useState, useCallback } from 'react';
import http from '@/lib/request';
import { prixUrl } from '@/lib/conifg';
import Loading from '@/components/Loading';

// 自定义消息提示组件
const Message = {
  error: (content: string) => alert(content),
  warning: (content: string) => alert(content),
};

// 发送图标
const SendIcon = () => (
  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
  </svg>
);

interface Message {
	role: 'user' | 'assistant';
	content: string;
}

const Nl2Sql: React.FC = () => {
	const [result, setResult] = useState<any[]>([]);
	const [threadId, setThreadId] = useState('');
	const [historyArray, setHistoryArray] = useState<Message[]>([]);
	const [msg, setMsg] = useState('');
	const [loading, setLoading] = useState(false);

	const createThread = async () => {
		const id = crypto.randomUUID();
		try {
			const res: any = await http.post(`${prixUrl}/threads`, {
				thread_id: id,
				metadata: {
					name: sessionStorage.getItem('username') || 'unknown',
				},
				if_exists: 'raise',
				ttl: {
					strategy: 'delete',
					ttl: 1,
				},
			});
			console.log('----> res', res);
			if (res.thread_id) {
				setThreadId(res.thread_id);
			}
			return id;
		} catch (error) {
			console.error('创建线程失败:', error);
			Message.error('创建线程失败，请重试');
			return null;
		}
	};

	const getData = useCallback(async () => {
		if (!threadId) {
			Message.error('线程ID不存在，请重新创建');
			return;
		}

		setLoading(true);
		try {
			const res: any = await http.post(`${prixUrl}/threads/${threadId}/runs/stream`, {
				assistant_id: '23be36d7-3cd9-4493-b399-5720566ef918',
				stream: true,
				input: {
					question: msg,
				},
			});

			const reader = res.body?.getReader();
			if (!reader) {
				Message.error('无法读取响应流');
				setLoading(false);
				return;
			}

			const decoder = new TextDecoder();
			const process = async ({ done, value }: any): Promise<any> => {
				if (done) {
					setLoading(false);
					return;
				}
				try {
					const text = decoder.decode(value);
					const lines = text.split('\n');
					const dataLine = lines.find((line: string) => line.startsWith('data: '));
					
					if (dataLine) {
						const data = JSON.parse(dataLine.substring(6));
						setResult((prev) => [...prev, data]);
						
						if (data.status === 'completed') {
							setLoading(false);
							return;
						}
						if (data.status === 'failed') {
							Message.error('处理失败');
							setLoading(false);
							return;
						}
						if (data.explanation) {
							setHistoryArray((prev) => [
								...prev.slice(0, prev.length - 1),
								{ role: 'assistant', content: data.explanation },
							]);
						}
					}
				} catch (e) {
					console.error('流处理出错:', e);
					Message.error('数据处理出错');
					setLoading(false);
				}
				return reader.read().then(process);
			};

			reader.read().then(process);
		} catch (error) {
			console.error('请求出错:', error);
			Message.error('请求失败，请重试');
			setLoading(false);
		}
	}, [threadId, msg]);
	const handleClickSend = useCallback(() => {
		if (!msg.trim()) {
			Message.warning('请输入问题');
			return;
		}

		setHistoryArray(prev => [
			...prev,
			{ role: 'user', content: msg },
			{ role: 'assistant', content: '' },
		]);
		getData();
		setMsg('');
	}, [msg, getData]);

	const handleKeyPress = (e: React.KeyboardEvent) => {
		if (e.key === 'Enter' && !e.shiftKey) {
			e.preventDefault();
			handleClickSend();
		}
	};

	useEffect(() => {
		console.log('Nl2Sql');
		createThread();
	}, []);

	return (
		<div className="h-full relative flex flex-col">
			<div className="flex-1 overflow-y-auto p-4">
				{historyArray.map((item, index) => (
					<div
						key={index}
						className={`${
							item.role === 'user' 
								? 'bg-blue-50 ml-8' 
								: 'bg-gray-50 mr-8'
						} p-3 rounded-lg mb-3 shadow-sm`}
					>
						<div className="font-semibold text-sm text-gray-600 mb-1">
							{item.role === 'user' ? '用户' : 'AI助手'}
						</div>
						<div className="whitespace-pre-wrap">{item.content}</div>
					</div>
				))}
				{loading && (
					<div className="flex justify-center py-4">
						<Loading tip="AI正在思考中..." />
					</div>
				)}
			</div>
			
			<div className="border-t p-4 bg-white">
			<div className="flex gap-2">
				<textarea
					value={msg}
					onChange={(e) => setMsg(e.target.value)}
					onKeyUp={handleKeyPress}
					placeholder="请输入您的问题，按Enter发送，Shift+Enter换行"
					className="flex-1 p-3 border border-gray-300 rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-70 disabled:cursor-not-allowed"
					style={{ minHeight: '80px', maxHeight: '160px' }}
					disabled={loading}
				/>
				<button
					type="button"
					onClick={handleClickSend}
					disabled={loading || !msg.trim()}
					className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-70 disabled:cursor-not-allowed flex items-center gap-2 whitespace-nowrap"
				>
					{loading ? (
						<Loading tip="" size="small" />
					) : (
						<SendIcon />
					)}
					发送
				</button>
			</div>
		</div>
	</div>
);
};

export default Nl2Sql;
